INSTALL_INCLUDE ?= include
INSTALL_SOURCE ?= source

COPYRIGHT_FILE ?= ./COPYRIGHT
ifneq ($(shell cat $(COPYRIGHT_FILE) 2> /dev/null),)
COPYRIGHT ?= $(COPYRIGHT_FILE)
COPYRIGHT_DEP = $(COPYRIGHT_FILE)
else
COPYRIGHT ?= /dev/null
endif

PREFIX	?= $(DESTDIR)/usr/local
INCDIR	:= $(PREFIX)/$(INSTALL_INCLUDE)

SRCDIR	?= ./source
HEADERS	:= $(shell find -wholename "$(SRCDIR)/*.hpp" && find -wholename "$(SRCDIR)/*.h")
INCLUDE	:= $(HEADERS:$(SRCDIR)/%=$(INCDIR)/%)
INCDIRS	:= $(shell dirname $(INCLUDE))

INSTALL_SRCDIR	:= $(PREFIX)/$(INSTALL_SOURCE)
INSTALL_SOURCES	:= $(INCLUDE:$(INCDIR)/%=$(INSTALL_SRCDIR)/%)
INSTALL_SRCDIRS	:= $(shell dirname $(INSTALL_SOURCES))

default:
	@echo This is a pure header library, so there is nothing to build. You can still install/uninstall or test.

install_all: install install_source

install: $(INCLUDE)
	@echo Install complete!

$(INCDIR)/%.h: $(SRCDIR)/%.h $(COPYRIGHT_DEP)
	@mkdir -p $(@D)
	cat $(COPYRIGHT) > $@
	cat $< >> $@

$(INCDIR)/%.hpp: $(SRCDIR)/%.hpp $(COPYRIGHT_DEP)
	@mkdir -p $(@D)
	cat $(COPYRIGHT) > $@
	cat $< >> $@

install_source: $(INSTALL_SOURCES)

$(INSTALL_SRCDIR)/%: $(SRCDIR)/% $(COPYRIGHT_DEP)
	@mkdir -p $(@D)
	cat $(COPYRIGHT) > $@
	cat $< >> $@

uninstall:
	-rm $(INCLUDE)
	@rmdir -p $(INCDIRS) 2> /dev/null || true
	@echo Includes uninstalled!

uninstall_source:
	-rm $(INSTALL_SOURCES)
	@rmdir -p $(INSTALL_SRCDIRS) 2> /dev/null || true
	@echo Source code uninstalled!

uninstall_all: uninstall uninstall_source
	@echo Everything uninstalled!

ifneq ($(shell cat unit_tests/Makefile 2> /dev/null),)
TESTMAKE = +@$(MAKE) --no-print-directory -C unit_tests/
else
TESTMAKE = -@true
endif

test:
	@$(TESTMAKE)

test-clean:
	@$(TESTMAKE) clean

test-cleanrun:
	@$(TESTMAKE) cleanrun
	@$(TESTMAKE) run

test-all: test-clean test

clean: test-clean

.PHONY : clean uninstall test test-clean test-cleanrun test-all
